<?php


/**
 * The goal of this file is to allow developers a location
 * where they can overwrite core procedural functions and
 * replace them with their own. This file is loaded during
 * the bootstrap process and is called during the frameworks
 * execution.
 *
 * This can be looked at as a `master helper` file that is
 * loaded early on, and may also contain additional functions
 * that you'd like to use throughout your entire application
 *
 * @link: https://codeigniter4.github.io/CodeIgniter4/
 */

use App\Libraries\AES;


/**
 * @title 格式化输出数据
 * @param $object
 */
function halt($object)
{
    echo '<pre>';
    die(var_dump($object));
}

/**
 * @title 生成随机字符
 * @param int $pw_length
 * @return string
 */
function rand_str($length = 8)
{
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= chr(mt_rand(33, 126));
    }
    return $str;
}

/**
 * 清空删除指定目录
 * @param $path
 * @param bool $pathSelf
 */
function rm_dir($path, $pathSelf = true)
{
    if (empty($path) || !is_dir($path)) die('directory does not exist');
    $path = $path . '/';
    $dirFile = scandir($path);
    if (!empty($dirFile) && is_array($dirFile)) {
        foreach ($dirFile as $file) {
            if ($file != '.' && $file != '..') {
                $fullPath = $path . $file;
                if (is_dir($fullPath)) {
                    rm_dir($fullPath);
                } else {
                    unlink($fullPath);
                }
            }
        }
        if ($pathSelf) rmdir($path);
    }
}

/**
 * @title 压缩文件
 * @param array $files 待压缩文件 array('d:/test/1.txt'，'d:/test/2.jpg');【文件地址为绝对路径】
 * @param string $filePath 输出文件路径 【绝对文件地址】 如 d:/test/new.zip
 * @return string|bool
 */
function zip($files, $filePath)
{
    //检查参数
    if (empty($files) || empty($filePath)) {
        return false;
    }

    //压缩文件
    $zip = new ZipArchive();
    $zip->open($filePath, ZipArchive::CREATE);
    foreach ($files as $key => $file) {
        //检查文件是否存在
        if (!file_exists($file)) {
            return false;
        }
        $zip->addFile($file, basename($file));
    }
    $zip->close();

    return true;
}

/**
 * @title zip解压方法
 * @param string $filePath 压缩包所在地址 【绝对文件地址】d:/test/123.zip
 * @param string $path 解压路径 【绝对文件目录路径】d:/test
 * @return bool
 */
function unzip($filePath, $path)
{
    if (empty($path) || empty($filePath)) {
        return false;
    }

    $zip = new ZipArchive();

    if ($zip->open($filePath) === true) {
        $zip->extractTo($path);
        $zip->close();
        return true;
    } else {
        return false;
    }
}

/**
 * @title文件转base64
 * @param $image_file
 * @return string
 */
function file_to_base64img($image_file)
{
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . base64_encode($image_data);
    return $base64_image;
}

/**
 * @title base64转换成图片并保存到文件
 * @param $base64_image_content
 * @param $path
 * @param $file_type
 * @return bool|string
 */
function base64img_to_file($base64_image_content, $path, $file_type)
{
    $data = explode(',', $base64_image_content);
    if (is_array($data)) {
        $new_file = $path . "/" . date('Ymd', time()) . "/";
        if (!file_exists($new_file)) {
            mkdir($new_file, 0755);
        }
        $new_file_name = $new_file . time() . ".{$file_type}";
        $res = file_put_contents($new_file_name, base64_decode(str_replace($data[0], '', $base64_image_content)));
        if ($res) {
            return $new_file;
        } else {
            return false;
        }
    }
    throw new ErrorException('file resource exception');
}

/**
 * @title token 算法编码
 * @return string
 */
function accessToken_encode()
{
    $key_ary = [true, rand(100000, 999999), time()];
    $j_ = json_encode($key_ary);
    $j_rb_ = rand_str(6) . base64_encode($j_);
    AES::_init();
    $j_rb_oe_ = AES::OpensslEncrypt($j_rb_);
    $j_rb_oe_u_ = urlencode($j_rb_oe_);
    $j_rb_oe_u_r = rand_str(5) . $j_rb_oe_u_;
    return $j_rb_oe_u_r;
}

/**
 * @title token 算法解码
 * @param $j_rb_oe_u_r
 * @return mixed
 */
function accessToken_decode($j_rb_oe_u_r)
{
    $j_rb_oe_u_ = substr($j_rb_oe_u_r, 5);
    $j_rb_oe_ = urldecode($j_rb_oe_u_);
    AES::_init();
    $j_rb_ = AES::OpensslDecrypt($j_rb_oe_);
    $j_ = base64_decode(substr($j_rb_, 6));
    $key_ary = json_decode($j_, true);
    return $key_ary;
}

/**
 * @title sock 异步POST请求
 * @param $url
 * @param $params
 */
function sockPost($url, $params)
{
    $info = parse_url($url);
    extract($info);
    $query = http_build_query($params);
    if ($info['scheme'] == 'https') {
        $fp = stream_socket_client('ssl://' . $info["host"] . ':443', $errno, $errstr, 30);
    } elseif ($info['scheme'] == 'http') {
        $fp = stream_socket_client($info["host"] . ':80', $errno, $errstr, 30);
    }
    if (!$fp) die('client error');
    $head = "POST " . $path . "?" . $query . " HTTP/1.0\r\n";
    $head .= "Host: " . $host . "\r\n";
    $head .= "Referer: https://" . $host . $path . "\r\n";
    $head .= "Content-type: application/x-www-form-urlencoded\r\n";
    $head .= "Content-Length: " . strlen(trim($query)) . "\r\n";
    $head .= "Authorization: " . accessToken_encode() . "\r\n";
    $head .= "\r\n";
    $head .= trim($query) . "\r\n";
    fwrite($fp, $head);
//    while (!feof($fp)) {          #转换同步
//        echo fgets($fp, 128);
//    }
    fclose($fp);
}

#--------------------------------------------------------------------
# Error masking
#--------------------------------------------------------------------
#过滤替换
function masking_replace($replace = '#/')
{
    return $replace;
}

#过滤文件dir
function masking_dir()
{
    return array_filter([
        dirname(ROOTPATH),
        env('bot.path.root'),
        env('bot.path.devices'),
    ]);
}